//
//  RootViewController.m
//  DPGJ
//
//  Created by ZhuoLaiQiang@Gmail.com on 11-11-17.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "RootViewController.h"
#import "FileManagerCenter.h"
#import "StyleBoxButtonView.h"
#import "CoreDataManager.h"
#import "LFAccount.h"
#import "LoginViewController.h"
#import "LoginOperation.h"
#import "CustomNavigationController.h"
#import "StyleBoxButton.h"
#import "MyOrderViewIndexViewController.h"
#import "CONSTS.h"
#import "AutoLoginOperation.h"

@interface RootViewController() 

- (void)setStyleBox;
- (void)StyleBoxBtnPressed:(StyleBoxButton *)button;

- (void)loginSuccess;
- (void)getLOginUrlSuccess:(NSString *)loginUrl;
- (void)getLOginUrlFail:(NSString *)faileReason;

- (void)autoLogin;

@end

@implementation RootViewController

@synthesize styleBoxConfigArray         =           _styleBoxConfigArray;

@synthesize loginOperationQueue         =           _loginOperationQueue;
@synthesize autoLoginOperationQueue     =           _autoLoginOperationQueue;
@synthesize scrollView                  =           _scrollView;
@synthesize nextOperationClassName      =           _nextOperationClassName;


- (void)dealloc
{
    LF_RELEASE_SAFELY(_nextOperationClassName);
    LF_RELEASE_SAFELY(_styleBoxConfigArray);
    
    [_loginOperationQueue cancelAllOperations];
    LF_RELEASE_SAFELY(_loginOperationQueue);
    [_autoLoginOperationQueue cancelAllOperations];
    LF_RELEASE_SAFELY(_autoLoginOperationQueue);
    
    [_scrollView release];
    [super dealloc];
}

#pragma mark - View lifecycle
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //自动登陆，因为这个接口不稳定，所以暂时不使用
    //[self autoLogin];
    
    self.navigationItem.title = @"店铺管理专家";
    
    UIBarButtonItem *cancelButton = [[[UIBarButtonItem alloc] initWithTitle: @"店铺管家" 
                                                                      style: UIBarButtonItemStylePlain 
                                                                     target: self
                                                                     action: @selector(dd)] autorelease];
    
    self.navigationItem.backBarButtonItem = cancelButton;
    
    _scrollView.contentSize = CGSizeMake(320, 480 - 20 - 44);
    
    //获取plist文件内对btn的配置信息
    self.styleBoxConfigArray = [FileManagerCenter getDataFromePlist: MAIN_VIEW_ICON_CONFIGURE];
    
    //设置九宫格
    [self setStyleBox];
}

- (void)dd
{
    
}

- (void)viewDidUnload 
{
    [self setScrollView:nil];
    
    [super viewDidUnload];
}

#pragma mark - 自定义函数
- (void)setStyleBox     //设置九宫格
{
    StyleBoxButtonView *styleBoxButtonView; 
    
    int count = [_styleBoxConfigArray count];
    float space = 35.0f;
    float padding = (320.0f - space - space - 3 * 57) / 2;  //57是styleBoxButtonView的宽
    
    for (int i = 0; i < count; i++) 
    {
        NSDictionary *styleBoxBtnInfoDic = [_styleBoxConfigArray objectAtIndex: i];
        styleBoxButtonView = [StyleBoxButtonView getStyleBoxButtonViewWithClassName: [styleBoxBtnInfoDic objectForKey: @"className"]];
        [styleBoxButtonView.button setBackgroundImage:[UIImage imageNamed:[styleBoxBtnInfoDic objectForKey: @"background_image"]] 
                                             forState:UIControlStateNormal];//设置按钮图片
        
        CGRect frame = styleBoxButtonView.frame;
        
        frame.origin.x = (i % 3 ) * (frame.size.width + padding) + space;
        frame.origin.y = floor( i / 3) * (frame.size.height + 8) + 20;
        [styleBoxButtonView setFrame: frame];
        [styleBoxButtonView.button setBackgroundColor:[UIColor clearColor]];
        [styleBoxButtonView.button addTarget:self action:@selector(StyleBoxBtnPressed:) forControlEvents: UIControlEventTouchDown];
        styleBoxButtonView.label.text = [styleBoxBtnInfoDic objectForKey: @"title_image"];
        ITTDINFO(@"%@",styleBoxBtnInfoDic);
        //  styleBoxButtonView.button.className = [styleBoxBtnInfoDic objectForKey: @"className"];
        styleBoxButtonView.button.tag = i;
        styleBoxButtonView.button.showsTouchWhenHighlighted = YES;
        
        [self.scrollView addSubview: styleBoxButtonView];
    }
}

//用户点击了九宫格上的按钮，就会响应此方法
- (void)StyleBoxBtnPressed:(StyleBoxButton *)button
{
    LFAccount *account = [[CoreDataManager sharedCoreDataManager] getCurrentLoggedInAccount];
    
    NSString *token = [account.token stringByReplacingOccurrencesOfString: @" " withString: @""];
    
    if (token && [token length] > 0 && ![token isEqualToString: @""])    //如果有token,说明用户登陆过
    {
        //ITTDINFO(@"button.className = %@", button.className);
        Class className = NSClassFromString(button.className);
        UIViewController *viewController = [[[className alloc] init] autorelease];
        
        NSObject<EPGLTransitionViewDelegate> *transition;
        
        transition = [[[Demo3Transition alloc] init] autorelease];
        
        EPGLTransitionView *glview = [[[EPGLTransitionView alloc] 
                                       initWithView:self.navigationController.view
                                       delegate:transition] autorelease];
        
        [self.navigationController pushViewController: viewController animated: NO];
        
        [glview prepareTextureTo:viewController.navigationController.view];
        
        [glview setClearColorRed:0.0
                           green:0.0
                            blue:0.0
                           alpha:1.0];
        
        [glview startTransition];  
    }else
    {
        self.nextOperationClassName = button.className;
        
        LoginOperation *loginOperation = [[[LoginOperation alloc] initWithDelegat: self 
                                                                       successSel: @selector(getLOginUrlSuccess:) 
                                                                          failSel: @selector(getLOginUrlFail:)] autorelease];
        
        self.loginOperationQueue = [[[NSOperationQueue alloc] init] autorelease];
        [_loginOperationQueue addOperation: loginOperation];
        MBProgressHUD *mBProgressHUD = [MBProgressHUD showHUDAddedTo: self.view animated: YES];
        mBProgressHUD.labelText = MBPROGRESSHUD_MESSAGE;
    }
}

//- (void)loginSuccess:(NSString *)loginUrl
- (void)getLOginUrlSuccess:(NSString *)loginUrl
{
    //返回值   =   {"api":"com.taobao.wireless.mtop.getLoginUrl","v":"*","ret":["SUCCESS::接口调用成功"],"data":{"key":"26d76cd1-73a3-42fe-be2b-fec9f6611ed6","url":"http://m.taobao.com/mtop/bindApp.htm?token=26d76cd1-73a3-42fe-be2b-fec9f6611ed6"}}
    
    //去登陆页面
    LoginViewController *loginViewController = [[LoginViewController alloc] initWithLoginUrl: loginUrl];
    
    CustomNavigationController *customNavigationController = [[CustomNavigationController alloc] initWithRootViewController: loginViewController];
    
    
    
    
    NSObject<EPGLTransitionViewDelegate> *transition;
    
    transition = [[[Demo3Transition alloc] init] autorelease];
    
    EPGLTransitionView *glview = [[[EPGLTransitionView alloc] 
                                   initWithView:self.navigationController.view
                                   delegate:transition] autorelease];
    
    customNavigationController.navigationBar.tintColor = NAVIGATION_TINT_COLOR;
    [self.navigationController presentModalViewController: customNavigationController animated: NO];
    
    [glview prepareTextureTo: customNavigationController.view];
    // If you are using an "IN" animation for the "next" view set appropriate 
    // clear color (ie no alpha) 
    [glview setClearColorRed:0.0
                       green:0.0
                        blue:0.0
                       alpha:1.0];
    
    
    
    
    [glview startTransition];
    
    [loginViewController release];
    [customNavigationController release];
    
    [MBProgressHUD hideHUDForView: self.view animated: YES];
}

- (void)getLOginUrlFail:(NSString *)faileReason
{
    [MBProgressHUD hideHUDForView: self.view animated: YES];
    
#ifdef DEBUG
    if (!faileReason || [faileReason isEqualToString: @""]) 
    {
        faileReason = ALERT_MESSAGE;
    }
    showAlert(ALERT_TITLE, faileReason);
#else
    showAlert(ALERT_TITLE, ALERT_MESSAGE);
#endif
}

- (void)loginSuccess
{
    if (!_nextOperationClassName)
    {
        return;
    }
    
    Class nextOperationClass = NSClassFromString(_nextOperationClassName);
    UIViewController *nextOperationViewController = [[[nextOperationClass alloc] init] autorelease];
    [self.navigationController pushViewController: nextOperationViewController animated: YES];
}

- (void)autoLogin
{
    self.autoLoginOperationQueue = [[[NSOperationQueue alloc] init] autorelease];
    AutoLoginOperation *autoLoginOperation = [[[AutoLoginOperation alloc] initByD: self] autorelease];
    [self.autoLoginOperationQueue addOperation: autoLoginOperation];
}

#pragma mark - AutoLoginDelegate
- (void)autoLoginSuccess:(NSDictionary *)newUserInfo_
{
    
}

- (void)autologinFail:(NSDictionary *)failInfo
{
    if (failInfo)   //如果failInfo不为空，说明服务返回的json数据，这样近一步说明token可能无效了，所以要清空coreData 里的LFAccount，以让用户重新登陆
    {
        CoreDataManager *coreDataManager = [CoreDataManager sharedCoreDataManager];
        [coreDataManager clearAccountCoreData];
    }
}


@end
